package filter;

import com.alibaba.fastjson.JSON;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        所有的请求都到达这里，经过检查后，决定是否发给servlet
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String[] urls={"/api/books","api/activeUser","/api/hotBooks","/api.login","/api/register","/api/notice"};
        String path=request.getRequestURL().toString();
        System.out.println(path);
        boolean fangxing=false;
        for (String url:urls){
            if (path.indexOf(url)>0){
                fangxing=true;
                break;
            }
        }
        if (fangxing=false){
            HttpSession session=request.getSession();//这行代码会自动根据请求消息中头部set-cookie键带来的值来获取对应session
            //怎么分析这个session对象是新创建的，还是上次创建的；登陆时创建session添加一个属性user到里面
            Object user=session.getAttribute("user");
            Response build=null;
            if (user==null){//还没有登陆
                build=Response.build(ResponseCode.NOT_LOGIN);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSON(build).toString());
            }else {//已登录，放行，请求继续访问后面的servlet
                filterChain.doFilter(servletRequest,servletResponse);

            }
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
